package com.paic.mhis.mis.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.paic.mhis.mis.dao.MenuDao;
import com.paic.mhis.mis.data.Menu;

@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuDao menuDao;
	
	@Override
	public List<Menu> getMenus(String[] roles) {
		List<Menu> menus = menuDao.getMenus(roles);
		List<Menu> rootMenus = findAllRootMenus(menus);
		for (Menu m : rootMenus) {
			appendChildMenus(m, menus);
		}
		
		return rootMenus;
	}
	private List<Menu> findAllRootMenus(List<Menu> menus){
		ArrayList<Menu> result = new ArrayList<Menu>();
		for (Menu m : menus) {
			if (m.getParentId() == 0)
				result.add(m);
		}
		return result;
	}
	
	private void appendChildMenus(Menu parentMenu, List<Menu> menus) {
		for (Menu m : menus) {
			if (m.getParentId() == parentMenu.getId()) {
//				parentMenu.getChildren().add(m);
				parentMenu.addChild(m);
				appendChildMenus(m, menus);
			}
		}
	}
}
